package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    //使用这个数据类型来将数据转成json格式
    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf-8");

        //客户端传来的用户名
        String username = req.getParameter("username");
        System.out.println("123");
        //根据用户名在数据库中查找
        UserDao userDao = new UserDao();
        User user = userDao.selectByUserName(username);
        if(user == null){
            //如果不存在此用户,不是数据库里面，id可以为负数
            user = new User();
            user.setUserId(-1);
        }

        //如果存在此用户
        //将user通过json格式发送到客户端
        String respJson = objectMapper.writeValueAsString(user);
        //将user发送到客户端
        resp.getWriter().write(respJson);
        System.out.println(respJson);






    }
}
